package com.sky.controller.common;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
@CrossOrigin
@Builder
@Api(tags = "通用接口(图片文件上传)")
public class FileUploadController {
    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/fileUpload")
    @ApiOperation("上传图片文件")
    public Result<String> upload(MultipartFile file) throws IOException {
        log.info("上传图片文件");

        try {
            // 获取文件输入流
            String originalFilename = file.getOriginalFilename();
            String fileName = null;
            if (originalFilename != null) {
                fileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
            }

            // 文件的存储路径
            String filePath = aliOssUtil.upload(file.getBytes(), fileName);
            return Result.success(filePath);
        } catch (IOException e) {
            return Result.error(MessageConstant.UPLOAD_FAIL);
        }

    }
}
